package com.axx.android.subject;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.axx.android.LetterApp;
import com.axx.android.R;
import com.axx.android.base.BaseActivity;
import com.axx.android.common.BaseModel;
import com.axx.android.common.Constants;
import com.axx.android.common.SJRefreshView;
import com.axx.android.home.model.User;
import com.axx.android.letter.activity.RecipientActivity;
import com.axx.android.profile.auth.activity.LoginActivity;
import com.axx.android.utils.GsonUtils;
import com.axx.android.utils.HttpUtils;
import com.axx.android.utils.ImageLoader;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.loadmore.SimpleLoadMoreView;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class SubjectNowActivity extends BaseActivity {

    @Bind(R.id.rv_list)
    RecyclerView mRvList;
    @Bind(R.id.activity_subject_now)
    LinearLayout mActivitySubjectNow;
    @Bind(R.id.btn_write)
    Button mBtnWrite;
    @Bind(R.id.btn_history)
    Button mBtnHistory;
    @Bind(R.id.layout_refresh)
    SJRefreshView layoutRefresh;
    private int curPage = 1;
    private int pageSize = 10;
    private View headerView;

    private List<SubjectNow.SubjectDetailListBean> listBeanList = new ArrayList<>();
    private SubjectNowAdapter subjectNowAdapter;
    private SubjectNow data;
    private String subjectId;

    @Override
    public int getLayoutId() {
        return R.layout.activity_subject_now;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        subjectId = getIntent().getStringExtra("subjectId");
        initAdapter();
        EventBus.getDefault().register(this);

        if (!TextUtils.isEmpty(subjectId)) {
            mBtnHistory.setText("本期专题");
        } else {
            mBtnHistory.setText("往期专题");
        }

        layoutRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                curPage = 1;
                fetchSubject();
            }
        });
        layoutRefresh.post(new Runnable() {
            @Override
            public void run() {
                layoutRefresh.setRefreshing(true);
                curPage = 1;
                fetchSubject();
            }
        });

    }

    @Subscribe
    public void onRefreshEvent(RefreshEvent e) {
        curPage = 1;
        layoutRefresh.post(new Runnable() {
            @Override
            public void run() {
                layoutRefresh.setRefreshing(true);
                curPage = 1;
                fetchSubject();
            }
        });
    }

    private void initAdapter() {
        subjectNowAdapter = new SubjectNowAdapter(R.layout.view_item_subject_now, listBeanList);
        mRvList.setLayoutManager(new LinearLayoutManager(this));
        mRvList.setAdapter(subjectNowAdapter);
        subjectNowAdapter.setLoadMoreView(new SimpleLoadMoreView());
        subjectNowAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                curPage++;
                fetchSubject();
            }
        }, mRvList);

        subjectNowAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(SubjectNowActivity.this, SubjectCommentActivity.class);
                intent.putExtra("model", subjectNowAdapter.getData().get(position));
                startActivity(intent);
            }
        });
        subjectNowAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_image:
                        Intent intent = new Intent(SubjectNowActivity.this, RecipientActivity.class);
                        String json = GsonUtils.toJson(subjectNowAdapter.getData().get(position).getUser());
                        try {
                            User.UserListBean userListBean = GsonUtils.fromJson(json, new TypeToken<User.UserListBean>() {
                            });

                            LatLng from = new LatLng(LetterApp.curLocation.getLatitude(),LetterApp.curLocation.getLongitude());
                            LatLng to = new LatLng(subjectNowAdapter.getData().get(position).getUser().getLatitude(),subjectNowAdapter.getData().get(position).getUser().getLongitude());

                            float distance = AMapUtils.calculateLineDistance(from,to);
                            String stringTime = String.format(Locale.US, "%.2f", distance/1000);
                            userListBean.setDistance(Double.parseDouble(stringTime));

                            intent.putExtra("model", (Serializable) userListBean);
                            startActivity(intent);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        break;
                    case R.id.iv_up:
                        handleUp(subjectNowAdapter.getData().get(position));
                        break;

                }

            }
        });
    }

    private void handleUp(final SubjectNow.SubjectDetailListBean model) {
        if (LetterApp.authUser == null) {
            startActivity(new Intent(this, LoginActivity.class));
            return;
        }
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("id", model.getId());
        hashMap.put("subjectId", model.getSubjectId());
        hashMap.put("userId", LetterApp.authUser.getId());
        HttpUtils.post(Constants.Url.Subject.SUBJECT_UP, hashMap, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    BaseModel<Integer> stringBaseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<Integer>>() {
                    });
                    model.setGoodStatus(stringBaseModel.data);
                    if (stringBaseModel.data == 1) {
                        model.setGood(model.getGood() + 1);
                    } else {
                        model.setGood(model.getGood() - 1);
                    }
                    subjectNowAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError() {

            }
        });
    }

    private void fetchSubject() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("nowpage", curPage + "");
        hashMap.put("pagenum", pageSize + "");
        if (LetterApp.authUser != null) {
            hashMap.put("userId", LetterApp.authUser.getId());
        }
        if (!TextUtils.isEmpty(subjectId)) {
            hashMap.put("subjectId", subjectId);
        }
        HttpUtils.post(Constants.Url.Subject.SUBJECT_NOW, hashMap, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                layoutRefresh.setRefreshing(false);
                try {
                    BaseModel<SubjectNow> baseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<SubjectNow>>() {
                    });
                    if (baseModel.isSuccess()) {
                        showSuccessView(baseModel.data);
                    } else {
                        showToast(baseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                layoutRefresh.setRefreshing(false);
                showErrorNet();
            }
        });
    }

    private void showSuccessView(SubjectNow data) {
        this.data = data;
        showHeader(data.getSubject());
        showList(data.getSubjectDetailList());
    }

    private View getEmptyView() {
        return LayoutInflater.from(this).inflate(R.layout.view_default_emtpy, (ViewGroup) mRvList.getParent(), false);
    }

    private void showHeader(SubjectNow.SubjectBean subject) {
        if (subject == null)
            return;
        if (headerView == null) {
            headerView = LayoutInflater.from(this).inflate(R.layout.view_header_subject_now, (ViewGroup) mRvList.getParent(), false);
            ImageView imageView = (ImageView) headerView.findViewById(R.id.iv_bg);
            TextView textView = (TextView) headerView.findViewById(R.id.tv_title);

            ((TextView) headerView.findViewById(R.id.tv_comment_cnt)).setText(subject.getReply()+"");
            ((TextView) headerView.findViewById(R.id.tv_good_cnt)).setText(subject.getGood()+"");

            textView.setText(subject.getName());

            TextView title = (TextView) headerView.findViewById(R.id.tv_subject_title);
            if (TextUtils.isEmpty(subjectId)) {
                title.setText("本期专题");
            } else {
                title.setText("往期专题");
            }
            ImageLoader.loadImage(subject.getUrl(), imageView, this);
            subjectNowAdapter.addHeaderView(headerView);
        }
    }

    private void showList(List<SubjectNow.SubjectDetailListBean> data) {
        if (curPage == 1) {
            subjectNowAdapter.setNewData(data);
            subjectNowAdapter.disableLoadMoreIfNotFullPage(mRvList);
            if (data.size() == 0) {
                subjectNowAdapter.addHeaderView(getEmptyView(), 1);
            }
        } else {
            int loadCount = data.size();
            subjectNowAdapter.addData(data);
            if (loadCount < pageSize) {
                subjectNowAdapter.loadMoreEnd();
            } else {
                subjectNowAdapter.loadMoreComplete();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_write, R.id.btn_history})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_write:
                Intent intent = new Intent(SubjectNowActivity.this, SubjectWriteActivity.class);
                if (TextUtils.isEmpty(subjectId)) {
                    intent.putExtra("subjectId", data.getSubject().getId());
                } else {
                    intent.putExtra("subjectId", subjectId);
                }
                startCheckAuth(intent);
                break;
            case R.id.btn_history:
                if (!TextUtils.isEmpty(subjectId)) {
                    startActivity(new Intent(SubjectNowActivity.this, SubjectNowActivity.class));
                } else {
                    startActivity(new Intent(SubjectNowActivity.this, SubjectHistoryActivity.class));
                }

                break;
        }
    }
}
